package com.woniuxy.exam.controller;

import com.github.pagehelper.PageInfo;
import com.woniuxy.exam.entity.Book;
import com.woniuxy.exam.entity.BookCategory;
import com.woniuxy.exam.service.BookCategoryService;
import com.woniuxy.exam.service.BookService;
import com.woniuxy.exam.vo.BookVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Controller    //@RestController 和 @Controller的区别
@RequestMapping("book")
public class BookController {

    @Autowired
    BookService bookService ;

    @Autowired
    BookCategoryService categoryService ;


    @RequestMapping("/list")
    public String list(@RequestParam(value = "now",defaultValue = "1") Integer now,
                       @RequestParam(value = "size",defaultValue = "3") Integer size,
                       @RequestParam(value = "cid",defaultValue = "-1") Integer cid,
                       String bname ,Map map){
        //查询数据
        PageInfo<BookVo> pageInfo = bookService.findBookByPage(now, size, bname, cid);
        //查询图书类型
        List<BookCategory> categoryList = categoryService.findAll();
        //搜索条件
        map.put("pageInfo",pageInfo);
        map.put("clist",categoryList);
        map.put("bname",bname);
        map.put("cid",cid);

        return "book" ;
    }

    @RequestMapping("/addView")
    public String addView(Map map){
        //查询图书类型
        List<BookCategory> categoryList = categoryService.findAll();
        map.put("clist",categoryList);
        return "add" ;
    }
    @RequestMapping("/modifyView")
    public String modifyView(int id,Map map){
        //查询图书类型
        List<BookCategory> categoryList = categoryService.findAll();
        map.put("clist",categoryList);

        Book book = bookService.findBookByKey(id);
        map.put("book",book);
        return "update" ;
    }

    @RequestMapping("/add")
    public String addBook(Book book){
        bookService.add(book);
        return "redirect:list" ;
    }
    @RequestMapping("/modify")
    public String modify(Book book){
        bookService.modify(book);
        return "redirect:list" ;
    }

    @RequestMapping("/del")
    @ResponseBody //针对异步的
    public int del(int id) {
        int i = bookService.removeBookByKey(id);
        return i ;
    }

    @RequestMapping("/delBatch")
    @ResponseBody  //针对异步的
    public int delBatch(@RequestParam(value = "ids[]") int[] ids) {
        int i = bookService.removeBatch(ids);
        return i ;
    }
}
